#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/6/2 9:09
# @Author  : 1823218990@qq.com
# @File    : split_vc.py
# @Software: Pycharm

from datetime import datetime
import time
import shutil
import sys
import os
real_cfile = os.path.abspath(__file__)
real_path = os.path.dirname(real_cfile)
sys.path.append(real_path)
if not sys.platform.startswith("win"):
    raise Exception("can not run on this system: {}".format(sys.platform))
try:
    from vccut import VideaCut
except Exception as e:
    print(e)
    raise Exception(e)


class SplitVc(object):
    def __init__(self, inputfile, outputfile, split_list):
        self.inputfile = inputfile
        self.outputfile = outputfile
        self.split_list = split_list
        self.temp_dir = "\\tmp\\vccut"
        self.check_args()

    def check_args(self):
        if not os.path.exists(self.inputfile):
            raise Exception("{} not fount".format(self.inputfile))
        if not os.path.exists(self.temp_dir):
            os.makedirs(self.temp_dir)

        if os.path.isdir(self.outputfile):
            raise Exception("{} is dir".format(self.outputfile))
        else:
            if not os.path.exists(os.path.dirname(self.outputfile)):
                os.makedirs(os.path.dirname(self.outputfile), exist_ok=True)
        if not os.path.exists(self.temp_dir):
            os.makedirs(self.temp_dir)
        else:
            shutil.rmtree(self.temp_dir)
            os.makedirs(self.temp_dir, exist_ok=True)

    def split_cv_by_list(self):
        vccut = VideaCut(inputfile=self.inputfile, outputfile=self.outputfile)
        _name, _type = os.path.splitext(os.path.basename(self.inputfile))
        index = 0
        temp_file = os.path.join(self.temp_dir, "flist.txt")
        for split_item in self.split_list:
            stime, etime = split_item
            print(stime, etime)
            tmp_name = "{}{}".format(index, _type)
            tmp_outfile = os.path.join(self.temp_dir, tmp_name)
            vccut.set_out_file(tmp_outfile)
            vccut.cut_video_by_range_time(stime, etime)
            with open(temp_file, 'a+') as f:
                f.write("file '{}'".format(tmp_name))
                f.write('\n')

            index += 1

        vccut.set_out_file(self.outputfile)
        vccut.merge_video_by_file(temp_file)


def old_test():
    inputfile = "D:\\opt\\jq_01.mp4"
    outputfile = "D:\\opt\\output.mp4"
    split_list = [
        ['00:10:00', '00:12:00'],
        ['00:19:22', '00:20:00']
    ]

    sc = SplitVc(inputfile, outputfile, split_list)
    sc.split_cv_by_list()


def add_time(time_str):
    from datetime import datetime, timedelta

    # 初始时间转为datetime.time对象
    initial_time = datetime.strptime(time_str, "%H:%M:%S")

    # 加上29秒
    new_time = initial_time + timedelta(seconds=29)

    # 格式化输出为字符串（如果需要）
    new_time_str = new_time.strftime("%H:%M:%S")
    # print(new_time_str)
    return new_time_str


def test_sqlit():
    my_dict = {
        "风云1_01.mkv": [["00:07:06", "00:08:22"], ["00:10:49", "00:12:06"], ["00:16:36", "00:18:01"],
                       ["00:24:16", "00:26:12"], ["00:43:35", "00:45:10"]],

        "风云1_02.mkv": [["00:01:14", "00:01:55"], ["00:39:45", "00:40:12"]],

        "风云1_03.mkv": [["00:20:24", "00:20:38"], ["00:28:50", "00:29:40"]],

        "风云1_04.mkv": [["00:26:40", "00:27:42"]],

        "风云1_05.mkv": [["00:02:30", "00:07:50"], ["00:24:35", "00:26:30"], ["00:28:50", "00:29:10"]],

        "风云1_07.mkv": [["00:38:10", "00:38:51"]],

        "风云1_09.mkv": [["00:10:18", "00:11:35"]],

        "风云1_10.mkv": [["00:03:10", "00:04:05"], ["00:19:50", "00:23:05"]],

        "风云1_11.mkv": [["00:03:10", "00:04:05"], ["00:19:50", "00:23:05"]],

        "风云1_12.mkv": [["00:13:05", "00:18:20"]],

        "风云1_13.mkv": [["00:06:40", "00:07:16"], ["00:10:42", "00:11:21"], ["00:19:15", "00:19:37"],
                       ["00:38:42", "00:39:18"],
                       ["00:41:35", "00:42:13"]],

        "风云1_15.mkv": [["00:18:20", "00:21:30"]],

        "风云1_16.mkv": [["00:21:10", "00:22:28"]],

        "风云1_17.mkv": [["00:00:03", "00:02:11"], ["00:05:01", "00:05:36"]],

        "风云1_18.mkv": [["00:02:57", "00:03:30"], ["00:12:18", "00:13:01"], ["00:15:50", "00:16:34"],
                       ["00:21:25", "00:23:02"]],

        "风云1_20.mkv": [["00:03:25", "00:04:22"], ["00:32:19", "00:33:22"]],

        "风云1_21.mkv": [["00:24:02", "00:25:38"], ["00:32:38", "00:34:08"]],

        "风云1_22.mkv": [["00:08:46", "00:11:55"]],

        "风云1_23.mkv": [["00:38:13", "00:40:53"]],

        "风云1_24.mkv": [["00:33:35", "00:34:35"]],

        "风云1_27.mkv": [["00:06:39", "00:08:00"], ["00:11:15", "00:12:06"], ["00:26:37", "00:27:30"]],

        "风云1_28.mkv": [["00:27:11", "00:28:35"]],

        "风云1_29.mkv": [["00:40:28", "00:41:20"]],

        "风云1_31.mkv": [["00:00:36", "00:01:30"], ["00:02:18", "00:02:35"]],

        "风云1_32.mkv": [["00:02:50", "00:04:32"]],

        "风云1_33.mkv": [["00:11:20", "00:20:16"], ["00:30:50", "00:35:40"]],

        "风云1_35.mkv": [["00:40:08", "00:40:43"]],

        "风云1_36.mkv": [["00:09:39", "00:10:18"], ["00:13:17", "00:13:37"], ["00:18:45", "00:19:40"]],

        "风云1_42.mkv": [["00:14:40", "00:17:06"]],

        "风云1_43.mkv": [["00:39:50", "00:40:15"]],

        "风云1_44.mkv": [["00:23:50", "00:25:21"], ["00:33:01", "00:38:00"]],
    }

    origin_path = "G:\\我的视频\\风云1"
    for inputfile, split_list in my_dict.items():
        print(inputfile, split_list)
        outputfile = "G:\\我的视频\\风云1精华版\\all.mp3"
        temp_dir = "G:\\我的视频\\风云1精华版"
        inputfile_real = os.path.join(origin_path, inputfile)
        vccut = VideaCut(inputfile=inputfile_real, outputfile=outputfile)
        _name, _type = os.path.splitext(os.path.basename(inputfile))
        index = 0
        temp_file = os.path.join(temp_dir, "flist.txt")
        for split_item in split_list:
            stime, etime = split_item
            # stime = add_time(stime)
            # etime = add_time(etime)
            print(stime, etime)
            tmp_name = "{}_{}{}".format(inputfile, index, _type)
            tmp_outfile = os.path.join(temp_dir, tmp_name)
            vccut.set_out_file(tmp_outfile)
            vccut.cut_video_by_range_time(stime, etime)
            with open(temp_file, 'a+') as f:
                f.write("file '{}'".format(tmp_name))
                f.write('\n')

            index += 1

        # vccut.set_out_file(outputfile)
        # vccut.merge_video_by_file(temp_file)


if __name__ == '__main__':
    test_sqlit()